import json
import re
import requests
from django.conf import settings

class DeepSeekClient:
    def __init__(self):
        self.api_key = getattr(settings, 'DEEPSEEK_API_KEY', '')
        self.base_url = "https://api.deepseek.com/v1/chat/completions"
    
    def chat(self, message, max_tokens=4000):
        """调用DeepSeek API"""
        if not self.api_key:
            return {"error": "DeepSeek API密钥未配置"}
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
        
        payload = {
            "model": "deepseek-chat",
            "messages": [
                {
                    "role": "user",
                    "content": message
                }
            ],
            "max_tokens": max_tokens,
            "temperature": 0.1
        }
        
        try:
            response = requests.post(self.base_url, headers=headers, json=payload, timeout=30)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"error": f"API调用失败: {str(e)}"}

class CredentialParser:
    """账号密码文件解析器"""
    
    @staticmethod
    def parse_with_deepseek(file_content, filename):
        """使用DeepSeek解析账号密码文件"""
        prompt = f"""
        请解析以下账号密码数据，返回严格的JSON格式。数据格式包含：序号、位置、设备名称、用户名、密码、URL、状态、备注等信息。

        解析要求：
        1. 提取每条记录的完整信息
        2. 识别状态：系统正常、网址打不开、基本废弃、警告等
        3. 标准化URL格式（确保是完整的URL）
        4. 识别协议类型：HTTPS、HTTP、SSH、Telnet等
        5. 返回格式必须严格遵循：
        {{
            "credentials": [
                {{
                    "location": "位置",
                    "device_name": "设备名称", 
                    "username": "用户名",
                    "password": "密码", 
                    "url": "访问地址",
                    "protocol": "协议类型",
                    "status": "状态",
                    "notes": "备注"
                }}
            ],
            "total_count": 总数,
            "success_count": 成功解析数,
            "file_name": "{filename}"
        }}

        数据内容：
        {file_content}

        注意：只返回JSON格式，不要其他文字说明。
        """
        
        client = DeepSeekClient()
        response = client.chat(prompt)
        
        return CredentialParser.extract_json_from_response(response)
    
    @staticmethod
    def extract_json_from_response(response):
        """从DeepSeek响应中提取JSON数据"""
        try:
            if isinstance(response, dict) and 'choices' in response:
                content = response['choices'][0]['message']['content']
            else:
                content = str(response)
            
            # 清理响应内容，提取JSON
            content = content.strip()
            if content.startswith('```json'):
                content = content[7:]
            if content.endswith('```'):
                content = content[:-3]
            
            # 提取JSON部分
            json_match = re.search(r'\{.*\}', content, re.DOTALL)
            if json_match:
                json_str = json_match.group()
                result = json.loads(json_str)
                
                # 验证必要字段
                if 'credentials' in result:
                    return result
                else:
                    return {"error": "解析结果格式不正确", "credentials": []}
            else:
                return {"error": "未找到有效的JSON数据", "credentials": []}
                
        except json.JSONDecodeError as e:
            return {"error": f"JSON解析失败: {str(e)}", "credentials": []}
        except Exception as e:
            return {"error": f"解析过程出错: {str(e)}", "credentials": []}
    
    @staticmethod
    def parse_file_content(file, filename):
        """根据文件类型读取内容"""
        file_ext = filename.split('.')[-1].lower()
        
        try:
            if file_ext == 'txt':
                content = file.read().decode('utf-8')
            elif file_ext in ['xlsx', 'xls']:
                import pandas as pd
                df = pd.read_excel(file)
                content = df.to_string()
            elif file_ext == 'docx':
                from docx import Document
                doc = Document(file)
                content = '\n'.join([para.text for para in doc.paragraphs])
            elif file_ext == 'pdf':
                import pdfplumber
                content = ''
                with pdfplumber.open(file) as pdf:
                    for page in pdf.pages:
                        content += page.extract_text() + '\n'
            else:
                content = file.read().decode('utf-8', errors='ignore')
            
            return content
        except Exception as e:
            raise Exception(f"文件读取失败: {str(e)}")